package com.suxin.shiro.jwt.filter;

import com.suxin.shiro.jwt.controller.JwtUtils;
import com.suxin.shiro.jwt.exception.CustomExpiredJwtException;
import com.suxin.shiro.jwt.token.JwtToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Tang
 * @classname JwtFilter
 * https://blog.csdn.net/wws_p/article/details/107126321
 * @description [ token效验权限问题 ]
 * @date 2021/3/21 21:29
 */
public class JwtFilter extends BasicHttpAuthenticationFilter {

    public RedisTemplate<String, Object> redisTemplate;

    public JwtFilter(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    /**
     * isAccessAllowed 返回false,会调用此方法
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return executeLogin(request, response);
    }

    /**
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        // 创建token
        AuthenticationToken token = createToken(request, response);
        if (token instanceof JwtToken) {
            JwtToken jwtToken = (JwtToken) token;
            if (StringUtils.isEmpty(jwtToken.getToken())) {
                throw new AuthenticationException();
            }
            // 手动登录
            try {
                Subject subject = getSubject(request, response);
                subject.login(token);
                return onLoginSuccess(token, subject, request, response);
            } catch (AuthenticationException e) {
                return onLoginFailure(token, e, request, response);
            }
        }
        return false;
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        // 强转 HttpServletRequest
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        String token = httpServletRequest.getHeader(AUTHORIZATION_HEADER);
        // 创建我们自定义的token
        if (!StringUtils.isEmpty(token)) {
            Jws<Claims> claimsJws = JwtUtils.parseJwt(token);
            // 开启缓存时，需要用户名查缓存
            if (claimsJws != null) {
                Object username = claimsJws.getBody().get("username");
                // 从redis获取用户密码
                SimpleAuthenticationInfo authenticationInfo =
                        (SimpleAuthenticationInfo) this.redisTemplate.opsForHash()
                        .get("AuthenticationCache", username);
                assert authenticationInfo != null;
                //     必须要构造 用户名 + 密码，shiro 需要对比。
                return new JwtToken(token, username,authenticationInfo.getCredentials().toString());
            }
        }
        throw new CustomExpiredJwtException("jwt 过期了...");
    }

    /**
     * 最先调用的方法  preHandle ---》 isAccessAllowed(返回false) ---》 onAccessDenied ---》 executeLogin
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}